<template>
  <el-dialog v-model="visible" :title="`${paramsProps.title}`" :destroy-on-close="true" width="580px" draggable>
    <el-form
      ref="ruleFormRef"
      label-width="100px"
      label-suffix=" :"
      :rules="rules"
      :model="formData"
      @submit.enter.prevent="handleSubmit"
    >
      <el-form-item label="公司名称" prop="name">
        <el-input v-model="formData.name" placeholder="请填写公司名称" clearable></el-input>
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input-number v-model="formData.sort" :precision="0" :min="0" :max="999999" />
      </el-form-item>
      <el-form-item label="负责人" prop="leaders">
        <el-select
          v-model="formData.leaders"
          multiple
          clearable
          placeholder="请选择负责人"
          style="width: 100%"
        >
          <el-option
            v-for="item in leaderOptions"
            :key="item.id"
            :label="item.name"
            :value="item"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="visible = false"> 取消</el-button>
      <el-button type="primary" @click="handleSubmit"> 确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { type ElForm, ElMessage } from 'element-plus';
import http from '@/api';
import { ADMIN_MODULE } from '@/api/helper/prefix';
import type { IResultData } from '@/api/types';

defineOptions({
  name: 'CompanyForm'
});

// 负责人数据
const leaderOptions = ref<{ id: number; name: string }[]>([]);

// 定义负责人数据类型
interface LeaderInfo {
  id: number;
  nickname: string;
}

// 获取负责人列表
const getLeaderList = async () => {
  try {
    const res = await http.get(`${ADMIN_MODULE}/sys-dept/leader`);
    // 将返回的数据转换为组件需要的格式
    const data = res.data as { leaderInfoVOS: LeaderInfo[] } | undefined;
    leaderOptions.value = data && Array.isArray(data.leaderInfoVOS)
      ? data.leaderInfoVOS.map((item: LeaderInfo) => ({
          id: item.id,
          name: item.nickname
        }))
      : [];
  } catch (error) {
    console.error('获取负责人列表失败:', error);
    ElMessage.error('获取负责人列表失败');
  }
};

const rules = reactive({
  name: [{ required: true, message: '请填写公司名称' }],
  sort: [{ required: true, message: '请填写排序' }]
});

const visible = ref(false);
const formData = ref({
  id: undefined as number | undefined,
  name: '',
  sort: 0,
  leaders: [] as any[]
});

const paramsProps = ref<{
  title: string;
  row: any;
  api: Function | undefined;
  getTableList: Function | undefined;
}>({
  title: '',
  row: {},
  api: undefined,
  getTableList: undefined
});

// 接收父组件传过来的参数
const acceptParams = (params: any) => {
  paramsProps.value = params;
  if (params.row) {
    formData.value = {
      id: params.row.id,
      name: params.row.name || '',
      sort: params.row.sort || 0,
      leaders: params.row.leaders || []
    };
  } else {
    // 重置表单
    formData.value = {
      id: undefined,
      name: '',
      sort: 0,
      leaders: []
    };
  }
  visible.value = true;
};

// 提交数据（新增/编辑）
const ruleFormRef = ref<InstanceType<typeof ElForm>>();
const handleSubmit = () => {
  ruleFormRef.value!.validate(async (valid) => {
    if (!valid) return;
    try {
      const submitData = {
        id: formData.value.id,
        name: formData.value.name,
        sort: formData.value.sort,
        leaders: formData.value.leaders
      };
      await paramsProps.value.api!(submitData);
      ElMessage.success({ message: `${paramsProps.value.title}成功！` });
      paramsProps.value.getTableList!();
      visible.value = false;
    } catch (error) {
      console.log(error);
    }
  });
};

// 页面加载时获取负责人数据
onMounted(() => {
  getLeaderList();
});

defineExpose({
  acceptParams
});
</script>

<style scoped lang="scss"></style>